<?php

namespace app\admin\controller\dts\approve;

use app\common\controller\Backend;
use Exception;
use think\Db;
use think\Log;
use PhpOffice\PhpSpreadsheet\IOFactory;
/**
 * 合同审批管理
 *
 * @icon fa fa-circle-o
 */
class Contract extends Backend
{

    /**
     * Contract模型对象
     * @var \app\admin\model\dts\approve\Contract
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\dts\approve\Contract;
        $this->view->assign("ispriceList", $this->model->getIspriceList());
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    protected $defaultJoin = [
        ['admin admin', 'admin.id = contract.admin_id', 'left'],
        ['dts_dept undertake_dept', 'undertake_dept.id = contract.undertake_dept_id', 'left'],
        ['admin undertake_admin', 'undertake_admin.id = contract.undertake_admin_id', 'left'],
        ['admin examine_dept', 'examine_dept.id = contract.examine_dept_id', 'left'],
        ['admin examine_leader', 'examine_leader.id = contract.examine_leader_id', 'left'],
        ['admin examine_finance', 'examine_finance.id = contract.examine_finance_id', 'left'],
        ['admin examine_advisor', 'examine_advisor.id = contract.examine_advisor_id', 'left'],
        ['admin examine_legal', 'examine_legal.id = contract.examine_legal_id', 'left'],
        ['admin copy', 'FIND_IN_SET(copy.id,contract.copy_ids)', 'left'],
    ];

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    public function index() {
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();
            
            $list = Db::name('dts_approve_contract')->alias('contract')
            ->field('contract.*,admin.nickname as admin__nickname,undertake_dept.name as undertake_dept__name,
            undertake_admin.nickname as undertake_admin__nickname,examine_dept.nickname as examine_dept__nickname,
            examine_leader.nickname as examine_leader__nickname,examine_finance.nickname as examine_finance__nickname,
            examine_advisor.nickname as examine_advisor__nickname,examine_legal.nickname as examine_legal__nickname,
            ifnull(GROUP_CONCAT(DISTINCT copy.nickname), "") copy__nickname')
            ->join($this->defaultJoin)
            ->where($where)
            ->order($sort, $order)
            ->group('contract.id')
            ->paginate($limit);

            $result = array("total" => $list->total(), "rows" => paginateList($list));

            return json($result);
        }

        return $this->view->fetch();
    }


    public function export($ids = null) {

        $row = Db::name('dts_approve_contract')->alias('contract')
        ->field('contract.*,admin.nickname as admin__nickname,undertake_dept.name as undertake_dept__name,undertake_admin.nickname as undertake_admin__nickname')
        ->join([
            ['admin admin', 'admin.id = contract.admin_id', 'left'],
            ['dts_dept undertake_dept', 'undertake_dept.id = contract.undertake_dept_id', 'left'],
            ['admin undertake_admin', 'undertake_admin.id = contract.undertake_admin_id', 'left'],
        ])
        ->where('contract.id', $ids)
        ->find();

        if(!$row) {
            $this->error('未查询到导出记录');
        }

        $row = paginateItem($row);

        $list = Db::name('dts_approve_examine_log')->alias('log')
        ->field('log.*,examine.nickname as examinename')
        ->join([
            ['admin examine', 'examine.id = log.examine_id', 'left']
        ])
        ->where(['log.category' => 'contract', 'log.approve_id' => $row['id']])
        ->order('log.id', 'asc')
        ->select();

        try {
            //读取模板
            $reader = IOFactory::createReader('Xlsx');
            $spreadsheet = $reader->load('template/contract.xlsx');
            //指向激活的工作表
            $worksheet = $spreadsheet->getActiveSheet();     
            $worksheet->setTitle('合同审批');
            $wizard = new \PhpOffice\PhpSpreadsheet\Helper\Html;

            //向模板表中写入数据
            $worksheet->getStyle('C3')->getAlignment()->setWrapText(true);
            $charset = mb_detect_encoding($row['name']);
            $name = preg_replace('/(.{100})/', "$1\n", $row['name']);
            $worksheet->setCellValue('C3', mb_convert_encoding($name, 'UTF-8', $charset));
            $worksheet->setCellValue('C5', $row['isprice'] ? '是' : '否');

            $worksheet->getStyle('E5')->getAlignment()->setWrapText(true);
            $charset = mb_detect_encoding($row['enquirymsg']);
            $enquirymsg = preg_replace('/(.{80})/', "$1\n", $row['enquirymsg']);
            $worksheet->setCellValue('E5', str_replace('?', '', mb_convert_encoding($enquirymsg, 'UTF-8', $charset)));

            $worksheet->setCellValue('C7', $row['filingsno']);
            $worksheet->setCellValue('C9', $row['undertake_dept']['name']);
            $worksheet->setCellValue('C11', $row['undertake_admin']['nickname']);
            $worksheet->setCellValue('C13', date('Y-m-d', strtotime($row['undertake_time'])));

            $worksheet->getStyle('C15')->getAlignment()->setWrapText(true);
            $charset = mb_detect_encoding($row['performing_party']);
            $performing_party = preg_replace('/(.{100})/', "$1\n", $row['performing_party']);
            $worksheet->setCellValue('C15', str_replace('?', '', mb_convert_encoding($performing_party, 'UTF-8', $charset)));

            $worksheet->getStyle('C17')->getAlignment()->setWrapText(true);
            $charset = mb_detect_encoding($row['content']);
            $content = preg_replace('/(.{100})/', "$1\n", $row['content']);
            $worksheet->setCellValue('C17', str_replace('?', '', mb_convert_encoding($content, 'UTF-8', $charset)));
            $worksheet->setCellValue('C24', $row['pay_agree']);
            $worksheet->setCellValue('C26', $row['pay_price']);
            $worksheet->setCellValue('C28', $row['pay_method']);
            $worksheet->setCellValue('C30', $row['deadline']);
            $worksheet->setCellValue('C32', $row['copies_num']);

            $key = 34;
            foreach($list as $item) {
                if($key > 50) {
                    break;
                }
                if($item['examine_refuse']) {
                    $worksheet->setCellValue('C'.$key, $item['examinename'] . '    ' . $item['examine_result'] . '（'.$item['examine_refuse'].'）');
                }else {
                    $worksheet->setCellValue('C'.$key, $item['examinename'] . '    ' . $item['examine_result']);
                }
                $worksheet->setCellValue('I'.$key, date('Y-m-d', $item['createtime']));
                $key = $key + 4;
            }

            //输出到浏览器
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header('Content-Disposition: attachment;filename="'.$row['name'].'.xlsx"');
            header('Cache-Control: max-age=0');
            
            ob_clean();
            ob_start();
            //按照指定格式生成Excel文件
            $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
            $writer->save('php://output');

            /* 释放内存输出 */
            ob_end_flush();

        }catch(Exception $e) {
            Log::write($e->getMessage());
        }


    }
}
